<?php

namespace Wintel\RestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class CallstatusController
 * @package Wintel\RestBundle\Controller
 */
class CallstatusController extends Controller
{
    /**
     * 坐席电话呼叫状态
     */
    const FORBIDDEN_CALL_IN_AND_OUT = 0;
    const ALLOWED_CALL_IN = 1;
    const ALLOWED_CALL_OUT = 2;
    const ALLOWED_CALL_IN_AND_OUT = 3;

    /**
     * @var array
     */
    private $callStatus = array(
        self::FORBIDDEN_CALL_IN_AND_OUT,
        self::ALLOWED_CALL_IN,
        self::ALLOWED_CALL_OUT,
        self::ALLOWED_CALL_IN_AND_OUT
    );

    /**
     * 参数对应的要更新的数据库的值
     * @var array
     */
    private $callStatusValue = array(
        self::FORBIDDEN_CALL_IN_AND_OUT => 0x000f,
        self::ALLOWED_CALL_IN => 0x0007,
        self::ALLOWED_CALL_OUT => 0x000b,
        self::ALLOWED_CALL_IN_AND_OUT => 0x0003
    );

    /**
     * 结果
     * @var array
     *
     */
    private $RENDRESULT = array(
        '0' => "接通",
        '1' => "振铃放弃",
        '2' => "未接",
    );

    private $RINRESULT = array(
        '0' => '接通',
        '1' => 'IVR挂机',
        '2' => '留言',
        '3' => '未接通',
        '4' => '未接通留言',
    );
    /**
     * 转接分配结果
     * @var array
     */
    private $TRANSCALL = array(
        '0' => '成功',
        '1' => '主叫放弃',
        '2' => '坐席未接',
        '3' => '排队超时',
        '4' => '排队溢出',
    );

    /**
     * @var array
     */
    private $QENDRESULT = array(
        '1' => '主叫放弃',
        '2' => '坐席未接',
        '3' => '排队超时',
        '4' => '队列满溢出',
        '11' => '用户挂机',
        '12' => '坐席挂断',
        '21' => '未转技能组',
    );

    private $CDRSTATUS = array(
        '0' => '待分配',
        '1' => '已分配',
        '2' => '处理中',
        '3' => '已完成',
    );

    /**
     * 设置坐席的电话是否开通呼入、呼出的权限
     *
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function callstatusAction(Request $request)
    {
        $vcc_id = $request->get('vcc_id', 0);
        $ag_id = $request->get('ag_id', 0);
        $call_status = $request->get('call_status', 0);

        if (empty($vcc_id)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID为空'
            );

            return new JsonResponse($ret);
        }

        if (empty($ag_id)) {
            $ret = array(
                'code' => 402,
                'message' => '坐席ID为空'
            );

            return new JsonResponse($ret);
        }

        if (!in_array($call_status, $this->callStatus)) {
            $ret = array(
                'code' => 403,
                'message' => '呼叫状态的值不在允许的范围[0,1,2,3]内'
            );

            return new JsonResponse($ret);
        }

        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get('doctrine.dbal.default_connection');
        $conn->beginTransaction();
        $tellevel = isset($this->callStatusValue[$call_status]) ? $this->callStatusValue[$call_status] : 0;

        try {
            $conn->executeQuery("UPDATE win_agent SET tellevel = (tellevel | $tellevel) WHERE id = ?", array($ag_id));
            $conn->commit();

            $ret = array(
                'code' => 200,
                'message' => 'ok'
            );

            return new JsonResponse($ret);
        } catch (Exception $e) {
            $conn->rollback();

            $ret = array(
                'code' => 404,
                'message' => '更新失败[' . implode('|', $conn->errorInfo()) . ']'
            );

            return new JsonResponse($ret);
        }
    }

    /** 呼出明细报表；
     * @param Request $request
     * @return JsonResponse
     */
    public function calloutAction(Request $request)
    {
        $vcc_code = $request->get("vcc_code", 0);
        $info = $request->get('info', ''); //分页搜索相关信息；
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get("doctrine.dbal.default_connection");

        //验证vcc_code;
        $msg = $vcc_id = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //分页搜索相关信息；
        $addInfo = array();
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return new JsonResponse(array('code' => 403, 'message'=>'info格式非json'));
            }
        }

        $where = '';
        $params = array();
        if (isset($addInfo['filter'])) {
            //坐席工号；
            $where.= isset($addInfo['filter']['ag_num']) && !empty($addInfo['filter']['ag_num']) ?
                " AND ag_num LIKE '%".$addInfo['filter']['ag_num']."%' " : '';
            //呼叫结果
            if (isset($addInfo['filter']['result']) && $addInfo['filter']['result'] !== '') {
                $result = $addInfo['filter']['result'] ;
                $where.=" AND result = :result ";
                $params['result'] = (int)$result;
            }

            //坐席号码；
            $where.= isset($addInfo['filter']['ag_phone']) && !empty($addInfo['filter']['ag_phone']) ?
                " AND ag_phone LIKE '%".$addInfo['filter']['ag_phone']."%' " : '';

            //客户号码
            $where.= isset($addInfo['filter']['cus_phone']) && !empty($addInfo['filter']['cus_phone']) ?
                " AND cus_phone LIKE '%".$addInfo['filter']['cus_phone']."%' " : '';

            //技能组
            if (isset($addInfo['filter']['que_id']) && !empty($addInfo['filter']['que_id'])) {
                $where.= " AND que_id = :que_id ";
                $params['que_id'] = (int)$addInfo['filter']['que_id'];
            }

            //开始时间
            if (isset($addInfo['filter']['start_time']) && !empty($addInfo['filter']['start_time'])) {
                $start_time = $addInfo['filter']['start_time'];
                $msg = $this->get('validator.extend.custom')->isDateTime('开始时间格式不正确', $start_time, 404);
                if (!empty($msg) && is_array($msg)) {
                    return new JsonResponse($msg);
                }
                $where.="AND start_time >= UNIX_TIMESTAMP('$start_time')";
            }

            //结束时间
            if (isset($addInfo['filter']['end_time']) && !empty($addInfo['filter']['end_time'])) {
                $end_time = $addInfo['filter']['end_time'];
                $msg = $this->get('validator.extend.custom')->isDateTime('结束时间格式不正确', $end_time, 405);
                if (!empty($msg) && is_array($msg)) {
                    return new JsonResponse($msg);
                }
                $where.="AND start_time <= UNIX_TIMESTAMP('$end_time')";
            }
        }
        $params['vcc_id'] = $vcc_id;
        $count = $conn->fetchColumn(
            'SELECT count(*) '.
            'FROM win_agcdr '.
            'WHERE vcc_id = :vcc_id AND call_type IN (1,3,5) '.$where,
            $params
        );
        $page = $this->get("validator.extend.custom")->getPageInfo($count, 'win_agcdr', $addInfo);
        $rows = $conn->fetchAll(
            "SELECT ag_name,ag_num,ag_phone,cus_phone,que_name,start_time,end_time,ring_secs,conn_secs,all_secs,result ".
            "FROM win_agcdr ".
            "WHERE vcc_id = :vcc_id AND call_type IN (1,3,5) ".$where.
            'ORDER BY '.$page['sort'].' '.$page['order'].' LIMIT '.$page['start'].','.$page['limit'],
            $params
        );

        $result = array();
        foreach ($rows as $k => $v) {
            $result[$k] = $v;
            $result[$k]['start_time'] = date("Y-m-d H:i:s", $v['start_time']);
            $result[$k]['end_time'] = date("Y-m-d H:i:s", $v['end_time']);
            $result[$k]['result'] = @$this->RENDRESULT[$v['result']];
        }

        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'total' => $count,
            'data' => $result,
        );
        return new JsonResponse($ret);
    }

    /**
     * 呼入明细
     * @param Request $request
     * @return JsonResponse
     *
     *
     */
    public function callinAction(Request $request)
    {
        $vcc_code = $request->get("vcc_code", 0);
        $info = $request->get('info', ''); //分页搜索相关信息；
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get("doctrine.dbal.default_connection");

        $msg = $vcc_id = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //分页搜索相关信息；
        $addInfo = array();
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return new JsonResponse(array('code' => 403, 'message'=>'info格式非json'));
            }
        }

        $where = '';
        $params = array();
        if (isset($addInfo['filter'])) {
            //坐席工号；
            $where.= isset($addInfo['filter']['ag_num']) && !empty($addInfo['filter']['ag_num']) ?
                " AND ag_num LIKE '%".$addInfo['filter']['ag_num']."%' " : '';
            //呼叫结果
            if (isset($addInfo['filter']['result']) && $addInfo['filter']['result'] !== '') {
                $result = $addInfo['filter']['result'] ;
                $where.=" AND result = :result ";
                $params['result'] = (int)$result;
            }

            //主叫号码；
            $where.= isset($addInfo['filter']['caller']) && !empty($addInfo['filter']['caller']) ?
                " AND caller LIKE '%".$addInfo['filter']['caller']."%' " : '';

            //被叫号码
            $where.= isset($addInfo['filter']['called']) && !empty($addInfo['filter']['called']) ?
                " AND called LIKE '%".$addInfo['filter']['called']."%' " : '';

            //技能组
            if (isset($addInfo['filter']['que_id']) && !empty($addInfo['filter']['que_id'])) {
                $where.= " AND que_id = :que_id ";
                $params['que_id'] = $addInfo['filter']['que_id'];
            }

            //业务组
            if (isset($addInfo['filter']['group_id']) && $addInfo['filter']['group_id'] !== '') {
                $group_id = $addInfo['filter']['group_id'] ;
                $where.=" AND group_id = :group_id ";
                $params['group_id'] = $group_id;
            }

            //开始时间
            if (isset($addInfo['filter']['start_time']) && !empty($addInfo['filter']['start_time'])) {
                $start_time = $addInfo['filter']['start_time'];
                $msg = $this->get('validator.extend.custom')->isDateTime('开始时间格式不正确', $start_time, 404);
                if (!empty($msg) && is_array($msg)) {
                    return new JsonResponse($msg);
                }
                $where.="AND start_time >= UNIX_TIMESTAMP('$start_time')";
            }

            //结束时间
            if (isset($addInfo['filter']['end_time']) && !empty($addInfo['filter']['end_time'])) {
                $end_time = $addInfo['filter']['end_time'];
                $msg = $this->get('validator.extend.custom')->isDateTime('结束时间格式不正确', $end_time, 405);
                if (!empty($msg) && is_array($msg)) {
                    return new JsonResponse($msg);
                }
                $where.="AND start_time <= UNIX_TIMESTAMP('$end_time')";
            }

        }
        $params['vcc_id'] = $vcc_id;
        $count = $conn->fetchColumn(
            'SELECT count(*) '.
            'FROM win_incdr '.
            'WHERE vcc_id = :vcc_id '.$where,
            $params
        );
        $page = $this->get("validator.extend.custom")->getPageInfo($count, 'win_incdr', $addInfo);
        $rows = $conn->fetchAll(
            "SELECT ag_name,call_id,cdr_status,server_num,caller,called,ag_num,que_name,start_time,quein_time,conn_time,end_time,ivr_secs,wait_secs,conn_secs,all_secs,result ".
            "FROM win_incdr ".
            "WHERE vcc_id = :vcc_id ".$where.
            'ORDER BY '.$page['sort'].' '.$page['order'].' LIMIT '.$page['start'].','.$page['limit'],
            $params
        );

        $result = array();
        foreach ($rows as $k => $v) {
            $result[$k]['server_num'] = $v['server_num'];
            $result[$k]['caller'] = $v['caller'];
            $result[$k]['called'] = $v['called'];
            $result[$k]['que_name'] = $v['que_name'];
            $result[$k]['ivr_secs'] = $v['ivr_secs'];
            $result[$k]['wait_secs'] = $v['wait_secs'];
            $result[$k]['conn_secs'] = $v['conn_secs'];
            $result[$k]['all_secs'] = $v['all_secs'];
            $result[$k]['call_id'] = $v['call_id'];
            $result[$k]['ag_num'] = $v['ag_num'];
            $result[$k]['ag_name'] = $v['ag_name'];
            $result[$k]['start_time'] = $v['start_time'] ? date("Y-m-d H:i:s", $v['start_time']) : "";
            $result[$k]['quein_time'] = $v['quein_time'] ? date("Y-m-d H:i:s", $v['quein_time']) : "";
            $result[$k]['conn_time'] = $v['conn_time'] ? date("Y-m-d H:i:s", $v['conn_time']) : "";
            $result[$k]['end_time'] = $v['end_time'] ? date("Y-m-d H:i:s", $v['end_time']) : "";
            $result[$k]['cdr_status'] = $v['result'] ? $this->CDRSTATUS[$v['cdr_status']] : "不分配";
            $result[$k]['result'] = @$this->RINRESULT[$v['result']];
        }

        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'total' => $count,
            'data' => $result,
        );
        return new JsonResponse($ret);
    }

    /**
     * 呼叫转接接口；
     * @param Request $request
     * @return JsonResponse
     *
     */
    public function transcallAction(Request $request)
    {
        $vcc_code = $request->get("vcc_code", 0);
        $call_id = $request->get("call_id", 0);
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->get("doctrine.dbal.default_connection");

        if (empty($vcc_code)) {
            $ret = array(
                'code' => 401,
                'message' => '企业代码为空',
            );
            return new JsonResponse($ret);
        }

        //根据企业代码查询出vcc_id
        $vcc_id = $conn->fetchColumn(
            " SELECT vcc_id FROM cc_ccods WHERE vcc_code = :vcc_code Limit 1 ",
            array('vcc_code'=>$vcc_code)
        );

        if (empty($vcc_id)) {
            $ret = array(
                'code' => 402,
                'message' => '企业代码不存在',
            );
            return new JsonResponse($ret);
        }

        if (empty($call_id)) {
            $ret = array(
                'code' => 403,
                'message' => 'call_id为空',
            );
            return new JsonResponse($ret);
        }

        /*if (!is_numeric($call_id)) {
            $ret = array(
                'code' => 404,
                'message' => 'call_id包含非数字字符',
            );
            return new JsonResponse($ret);
        }*/

        $rows = $conn->fetchAll(
            "SELECT que_name,ag_num,ag_name,ag_phone,ent_que_time,assign_time,link_time,end_time,que_secs,ring_secs,conn_secs,all_secs,result,endresult ".
            "FROM win_queue_cdr ".
            "WHERE vcc_id = :vcc_id AND call_id = :call_id ",
            array('vcc_id' => $vcc_id, 'call_id' => $call_id)
        );

        $result = array();
        foreach ($rows as $k => $v) {
            $result[$k]['que_name'] = $v['que_name'];
            $result[$k]['ag_num'] = $v['ag_num'];
            $result[$k]['ag_name'] = $v['ag_name'];
            $result[$k]['ag_phone'] = $v['ag_phone'];
            $result[$k]['ent_que_time'] = $v['ent_que_time'] ? date("Y-m-d H:i:s", $v['ent_que_time']) : "";
            $result[$k]['assign_time'] = $v['assign_time'] ? date("Y-m-d H:i:s", $v['assign_time']) : "";
            $result[$k]['link_time'] = $v['link_time'] ? date("Y-m-d H:i:s", $v['link_time']) : "";
            $result[$k]['end_time'] = $v['end_time'] ? date("Y-m-d H:i:s", $v['end_time']) : "";
            $result[$k]['que_secs'] = $v['que_secs'];
            $result[$k]['ring_secs'] = $v['ring_secs'];
            $result[$k]['conn_secs'] = $v['conn_secs'];
            $result[$k]['all_secs'] = $v['all_secs'];
            $result[$k]['result'] = empty($this->TRANSCALL[$v['result']]) ? '未设置' : $this->TRANSCALL[$v['result']];
            $result[$k]['endresult'] = empty($this->QENDRESULT[$v['endresult']]) ? '未设置' : $this->QENDRESULT[$v['endresult']];
        }

        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'data' => $result,
        );
        return new JsonResponse($ret);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * 获取自动外呼呼叫明细
     */
    public function accdrAction(Request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");
        $vcc_code =  $request->get('vcc_code', 0);
        $start_date = $request->get('start_time');
        $end_date = $request->get('end_time');

        //vcc_code 验证
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        if (!empty($start_date)) {
            //验证开始日期；
            $msg = $this->get('validator.extend.custom')->isDateTime('开始时间不正确', $start_date, 403);
            if (!empty($msg) && is_array($msg)) {
                return new JsonResponse($msg);
            }
        } else {
             $start_date = date("Y-m-d 00:00:00");
        }

        if (!empty($end_date)) {
            //验证开始日期；
            $msg = $this->get('validator.extend.custom')->isDateTime('结束时间不正确', $end_date, 404);
            if (!empty($msg) && is_array($msg)) {
                return new JsonResponse($msg);
            }
        } else {
            $end_date = date("Y-m-d 23:59:59");
        }

        $list = $conn->fetchAll(
            "SELECT vcc_id,call_id,pro_id,task_id,caller,called,start_time,ring_time,ans_time,conn_time,end_time,".
            "bill_sec,all_sec,result ".
            "FROM ac_cdr ".
            "WHERE vcc_id = :vcc_id AND start_time >= :start_time AND end_time <= :end_time ",
            array('vcc_id' => $vid, 'start_time' => strtotime($start_date), 'end_time' => strtotime($end_date))
        );

        $result = array();
        if (!empty($list)) {
            foreach ($list as $v) {
                $v['start_time'] = date('Y-m-d H:i:s', $v['start_time']);
                $v['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
                $v['ring_time'] = date('Y-m-d H:i:s', $v['ring_time']);
                $v['ans_time'] = !empty($v['ans_time']) ? date('Y-m-d H:i:s', $v['ans_time']) : 0;//有可能未应答
                $v['conn_time'] = !empty($v['conn_time']) ? date('Y-m-d H:i:s', $v['conn_time']) : 0;//有可能未接通
                $v['result'] = $v['result'] == 0 ? '接通' : '未接通';
                $result[] = $v;
            }
        }
        $ret = array('code'=>200, 'message'=>'ok', 'data'=>$result);
        return new JsonResponse($ret);
    }
}
